package com.wvmi.gmall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.wvmi.gmall.common.to.mq.SeckillOrderTo;
import com.wvmi.gmall.common.utils.R;
import com.wvmi.gmall.common.vo.MemberResponseVo;
import com.wvmi.gmall.seckill.config.GmallRabbitMQConfig;
import com.wvmi.gmall.seckill.feign.CouponFeignService;
import com.wvmi.gmall.seckill.feign.ProductFeignService;
import com.wvmi.gmall.seckill.interceptor.LoginUserInterceptor;
import com.wvmi.gmall.seckill.service.SeckillService;
import com.wvmi.gmall.seckill.to.SeckillSkuRedisTo;
import com.wvmi.gmall.seckill.vo.SeckillSessionWithSkusVo;
import com.wvmi.gmall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 描述:   <br>
 *
 * @author Wuminming <br>
 * 创建时间: 2023-12-08 11:50 <br>
 * <p>
 * Copyright: 2013 - 2023 www.szwcyq.com Inc. All rights reserved. <br>
 * 注意：本内容仅限于深圳市微创云启科技有限公司内部传阅，禁止外泄以及用于其他的商业目的<br>
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;
    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SECKILL_CHARE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Override
    public String kill(String killId, String key, Integer num) throws IOException {
        Object o = redisTemplate.opsForHash().get(SECKILL_CHARE_PREFIX, killId);
        if(o!=null){
            ObjectMapper objectMapper = new ObjectMapper();
            SeckillSkuRedisTo redisTo = objectMapper.readValue((String) o, SeckillSkuRedisTo.class);

            // 判断是否在秒杀期间
            long startTime = redisTo.getStartTime();
            long endTime = redisTo.getEndTime();
            long currentTimeMillis = System.currentTimeMillis();
            if(currentTimeMillis >= startTime && currentTimeMillis <= endTime){

                // 判断是否对应
                String randomCode = redisTo.getRandomCode();
                String killStr = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if(randomCode.equals(key) && killStr.equals(killId)){

                    //判断秒杀数量
                    if(redisTo.getSeckillLimit().equals(num)){
                        MemberResponseVo user = LoginUserInterceptor.LOGIN_USER.get();

                        //当前用户是否购买过此商品  userId_场次id_skuId
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(user.getId() + "_" + killStr, num.toString(), endTime - currentTimeMillis, TimeUnit.MILLISECONDS);
                        if(Boolean.FALSE.equals(ifAbsent)){

                            //信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            if (semaphore.tryAcquire(num)) {
                                String orderNo = IdWorker.getTimeId();
                                // 发送MQ
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(orderNo);
                                orderTo.setMemberId(user.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                orderTo.setSkuId(redisTo.getSkuId());
                                orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                rabbitTemplate.convertAndSend(GmallRabbitMQConfig.ORDER_EVENT_EXCHANGE,GmallRabbitMQConfig.ORDER_SECKILL_ORDER_ROUTE_KEY,orderTo);
                                return orderNo;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据skuId查询商品是否参加秒杀活动
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckilInfo(Long skuId) {

        //1、找到所有需要秒杀的商品的key信息---seckill:skus
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);

        //拿到所有的key
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            //4-45 正则表达式进行匹配
            String reg = "\\d-" + skuId;
            for (String key : keys) {
                //如果匹配上了
                if (Pattern.matches(reg,key)) {
                    //从Redis中取出数据来
                    String redisValue = hashOps.get(key);
                    //进行序列化
                    SeckillSkuRedisTo redisTo = JSON.parseObject(redisValue, SeckillSkuRedisTo.class);

                    //随机码
                    Long currentTime = System.currentTimeMillis();
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    //如果当前时间大于等于秒杀活动开始时间并且要小于活动结束时间
                    if (currentTime >= startTime && currentTime <= endTime) {
                        return redisTo;
                    }
                    redisTo.setRandomCode(null);
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        if(!CollectionUtils.isEmpty(keys)){
            long currentTimeMillis = System.currentTimeMillis();
            ObjectMapper objectMapper = new ObjectMapper();
            List<SeckillSkuRedisTo> resList = new ArrayList<>(30);
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] split = replace.split("_");
                long startTime = Long.parseLong(split[0]);
                long endTime = Long.parseLong(split[1]);
                if(currentTimeMillis >= startTime && currentTimeMillis <= endTime){
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    if(!CollectionUtils.isEmpty(range)){
                        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                        List<String> strings = hashOps.multiGet(range);
                        if(!CollectionUtils.isEmpty(strings)){
                            List<SeckillSkuRedisTo> collect = strings.stream().map(item -> {
                                try {
                                    return objectMapper.readValue(item, SeckillSkuRedisTo.class);
                                } catch (IOException ignored) {

                                }
                                return null;
                            }).collect(Collectors.toList());
                            resList.addAll(collect);
                        }
                    }
                }
            }
            return resList;
        }
        return new ArrayList<>();
    }

    @Override
    public void uploadSeckillSkuLatest3Days() throws IOException {
        //1、扫描最近三天的商品需要参加秒杀的活动
        R lates3DaySession = couponFeignService.getLates3DaySession();
        if (lates3DaySession.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkusVo> sessionData = lates3DaySession.getData("data", new TypeReference<List<SeckillSessionWithSkusVo>>() {});
            //缓存到Redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfo(sessionData);
        }
    }

    /**
     * 缓存秒杀活动信息
     * @param sessions
     */
    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessions) {
        if(!CollectionUtils.isEmpty(sessions)){
            sessions.forEach(session -> {

                //获取当前活动的开始和结束时间的时间戳
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();

                //存入到Redis中的key
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;

                //判断Redis中是否有该信息，如果没有才进行添加
                Boolean hasKey = redisTemplate.hasKey(key);
                //缓存活动信息
                if (Boolean.FALSE.equals(hasKey)) {
                    //获取到活动中所有商品的skuId
                    List<String> skuIds = session.getRelationSkus().stream()
                            .map(item -> item.getPromotionSessionId() + "-" + item.getSkuId().toString()).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key,skuIds);
                }
            });
        }
    }

    /**
     * 缓存秒杀活动所关联的商品信息
     * @param sessions
     */
    private void saveSessionSkuInfo(List<SeckillSessionWithSkusVo> sessions) {
        if (!CollectionUtils.isEmpty(sessions)) {
            sessions.forEach(session -> {
                //准备hash操作，绑定hash
                BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                session.getRelationSkus().forEach(seckillSkuVo -> {
                    //生成随机码
                    String token = UUID.randomUUID().toString().replace("-", "");
                    String redisKey = seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString();
                    if (Boolean.FALSE.equals(operations.hasKey(redisKey))) {

                        //缓存我们商品信息
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        Long skuId = seckillSkuVo.getSkuId();
                        //1、先查询sku的基本信息，调用远程服务
                        R info = productFeignService.getSkuInfo(skuId);
                        if (info.getCode() == 0) {
                            try {
                                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                                });
                                redisTo.setSkuInfo(skuInfo);
                            } catch (IOException e) {
                            }
                        }

                        //2、sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //3、设置当前商品的秒杀时间信息
                        redisTo.setStartTime(session.getStartTime().getTime());
                        redisTo.setEndTime(session.getEndTime().getTime());

                        //4、设置商品的随机码（防止恶意攻击）
                        redisTo.setRandomCode(token);

                        //序列化json格式存入Redis中
                        String seckillValue = JSON.toJSONString(redisTo);
                        operations.put(seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString(), seckillValue);

                        //如果当前这个场次的商品库存信息已经上架就不需要上架
                        //5、使用库存作为分布式Redisson信号量（限流）
                        // 使用库存作为分布式信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        // 商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    }
                });
            });
        }
    }
}
